package com.cn.kabalifemerchants.ui.user.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cn.kabalifemerchants.R;
import com.cn.kabalifemerchants.base.BasePresenter;
import com.cn.kabalifemerchants.base.IBaseActivity;
import com.cn.kabalifemerchants.base.MyApplication;
import com.cn.kabalifemerchants.config.LoginHelper;
import com.cn.kabalifemerchants.event.RxBus;
import com.cn.kabalifemerchants.event.RxBusBean;
import com.cn.kabalifemerchants.ui.login.LoginActivity;
import com.cn.kabalifemerchants.ui.login.adapter.AddressCheckAdapter;
import com.cn.kabalifemerchants.ui.login.bean.AddressProvinceListBean;
import com.cn.kabalifemerchants.ui.login.bean.MsgBean;
import com.cn.kabalifemerchants.ui.page.activity.RecruitListActivity;
import com.cn.kabalifemerchants.ui.page.activity.ServiceCaseListActivity;
import com.cn.kabalifemerchants.ui.page.bean.UpImgBean;
import com.cn.kabalifemerchants.ui.user.bean.MyUserInfoBean;
import com.cn.kabalifemerchants.utils.GlideEngine;
import com.cn.kabalifemerchants.utils.GlideUtil;
import com.cn.kabalifemerchants.utils.LoggerUtils;
import com.cn.kabalifemerchants.utils.RxToast;
import com.cn.kabalifemerchants.utils.SPUtil;
import com.cn.kabalifemerchants.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifemerchants.view.PopupWindow.CommonUtil;
import com.kongzue.dialog.listener.OnMenuItemClickListener;
import com.kongzue.dialog.v2.BottomMenu;
import com.kongzue.dialog.v2.SelectDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.db.CacheManager;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 晓林 on 2020/10/20.
 * function:
 */
public class UserInfoActivity extends IBaseActivity<UserInfoView, UserInfoPresenter> implements UserInfoView, CommonPopupWindow.ViewInterface {
    @BindView(R.id.img_user_head)
    CircleImageView imgUserHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_user_address_)
    TextView tv_user_address_;
    @BindView(R.id.tv_album)
    TextView tvAlbum;
    @BindView(R.id.tv_user_address)
    TextView tvUserAddress;


    public final static int CHOOSE_PHOTO_1 = 1001;
    private List<LocalMedia> selectHead = new ArrayList<>();
    String pathHead = "";//头像地址
    private int themeId;//
    private String[] choosePhotos;


    private CommonPopupWindow popupWindowAddress;


    List<AddressProvinceListBean.ResultBean> mListCitys;


    String province,
            city,
            area,
            street;
    int address1 = 0;
    int address2 = 0;
    int address3 = 0;
    int address4 = 0;
    int signAddress = 1;
    boolean isIsgn = true;
    //创建适配器
    AddressCheckAdapter addressCheckAdapter;

    @Override
    protected UserInfoPresenter createPresenter() {
        return new UserInfoPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onUserInfoData(LoginHelper.getLonginData().getResult());
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTitleBar("我的资料");
        choosePhotos = new String[]{getResources().getString(R.string.main_img_photograph), getResources().getString(R.string.main_img_album)};
        ///样式
        themeId = R.style.picture_default_style;
    }

    @OnClick({R.id.ll_btn_address_,R.id.ll_btn_money, R.id.tv_btn_next, R.id.ll_btn_head, R.id.ll_btn_name, R.id.ll_btn_album, R.id.ll_btn_cover, R.id.ll_btn_address, R.id.ll_btn_details, R.id.ll_btn_recruit, R.id.ll_btn_case})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_btn_money:
                //财务管理
                $startActivity(IMoneyActivity.class);
                break;
            case R.id.ll_btn_head:
                //todo 通选ing
                showBottomMenu(choosePhotos);
                break;
            case R.id.ll_btn_name:
                //todo 名称
                Bundle bundle = new Bundle();
                bundle.putString("name", tvName.getText().toString().trim());
                bundle.putInt("sign",1);
                $startActivity(UserInfoNameActivity.class, bundle);
                break;
            case R.id.ll_btn_address_:
                 bundle = new Bundle();
                bundle.putString("name", tv_user_address_.getText().toString().trim());
                bundle.putInt("sign",2);
                $startActivity(UserInfoNameActivity.class, bundle);
                break;
            case R.id.ll_btn_album:
                //todo 相册
                break;
            case R.id.ll_btn_cover:
                //todo 封面
                bundle = new Bundle();
                bundle.putString("img", LoginHelper.getUserData().getResult().getBusiness().getCover());
                $startActivity(CoverImgActivity.class, bundle);
                break;
            case R.id.ll_btn_address:
                //todo 地址
                //省
                isIsgn = true;
                if (signAddress == 4) {
                    signAddress = 4;
                    mPresenter.onCityListData(address3);
                } else {
                    signAddress = 1;
                    mPresenter.onProvinceListData();
                }

                break;
            case R.id.ll_btn_details:
                //todo 详情
                break;
            case R.id.ll_btn_recruit:
                //todo 招聘
                bundle = new Bundle();
                bundle.putInt("id", LoginHelper.getUserData().getResult().getBusiness().getId());
                $startActivity(RecruitListActivity.class, bundle);
                break;
            case R.id.ll_btn_case:
                //todo 案例管理
                bundle = new Bundle();
                bundle.putInt("id", LoginHelper.getUserData().getResult().getBusiness().getId());
                $startActivity(ServiceCaseListActivity.class, bundle);
                break;
            case R.id.tv_btn_next:
                SelectDialog.show(getMe(), "提示", "确定要退出吗？", "确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mPresenter.onUserOutData(LoginHelper.getLonginData().getResult());
                    }
                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                break;
        }
    }

    /**
     * 展示底部菜单选择
     *
     * @param strings 数组
     */
    private void showBottomMenu(String[] strings) {
        BottomMenu.show(this, strings, new OnMenuItemClickListener() {
            @Override
            public void onClick(String text, int index) {
                switch (index) {
                    case 1://TODO 相册
                        PictureSelector.create(UserInfoActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(themeId)
                                .selectionMode(PictureConfig.SINGLE)
                                .imageSpanCount(4)
                                .previewImage(true)
                                .isCamera(true)
                                .enableCrop(true)// 是否裁剪
                                .compress(true)// 是否压缩
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                .scaleEnabled(true)
                                .withAspectRatio(18, 18)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .forResult(CHOOSE_PHOTO_1);


                        break;
                    case 0://TODO 相机
                        // 单独拍照
                        PictureSelector.create(UserInfoActivity.this)
                                .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                                .loadImageEngine(GlideEngine.createGlideEngine())
                                .theme(themeId)
                                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                                .previewImage(true)// 是否可预览图片
                                .isCamera(true)// 是否显示拍照按钮
                                .enableCrop(true)// 是否裁剪
                                .compress(true)// 是否压缩
                                .scaleEnabled(true)
                                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                .withAspectRatio(18, 18)
                                .openClickSound(true)// 是否开启点击声音
                                .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                .minimumCompressSize(100)// 小于100kb的图片不压缩
                                .forResult(CHOOSE_PHOTO_1);//结果回调onActivityResult code
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
//            case onActivityResult_To_ComName:
//                if (data != null) {
//                    String name = data.getStringExtra("name");
//                    tvName.setText(name);
////                    String time = TimeUtils.getTime10();
////                    mPresenter.onUpUserInfoData(time, 1, name, LoginHelper.getLonginData().getInfo().getUuid());
//                }
//                break;
            case RESULT_OK:
                switch (requestCode) {
                    case CHOOSE_PHOTO_1:
                        // 图片选择结果回调
                        selectHead = PictureSelector.obtainMultipleResult(data);
                        // 例如 LocalMedia 里面返回三种path
                        // 1.media.getPath(); 为原图path
                        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                        // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                        for (LocalMedia media : selectHead) {
                            Log.i("图片-----》", media.getPath());

                            if (media.isCut() && !media.isCompressed()) {
                                // 裁剪过
                                pathHead = media.getCutPath();
                            } else if (media.isCompressed() || (media.isCut() && media.isCompressed())) {
                                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                                pathHead = media.getCompressPath();
                            } else {
                                // 原图
                                pathHead = media.getPath();
                            }
                            LoggerUtils.d("图片的地址=" + pathHead);
                            Glide.with(this).load(pathHead).into(imgUserHead);
                            //todo 上传头像
                            mPresenter.onUpImgData("head", pathHead);
                        }
                        break;
                }
            default:
                break;

        }
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onUpImgSuccess(UpImgBean bean) {
        mPresenter.onUpUserInfoData(LoginHelper.getLonginData().getResult(), bean.getResult().get(0));
    }

    @Override
    public void onUpUserInfoSuccess(MsgBean bean) {
        RxToast.success(bean.getMsg());
    }

    @Override
    public void onUserInfoSuccess(MyUserInfoBean bean) {
        GlideUtil.ImageLoad(getMe(), bean.getResult().getHead(), imgUserHead);
        tvName.setText(bean.getResult().getBusiness().getTitle());
        tv_user_address_.setText(bean.getResult().getBusiness().getAddress());
        tvAlbum.setText("照片 " + bean.getResult().getBusiness().getImg().size() + "张");
        tvUserAddress.setText(bean.getResult().getBusiness().getProvince_info() + bean.getResult().getBusiness().getCity_info() + bean.getResult().getBusiness().getArea_info() + bean.getResult().getBusiness().getStreet_info());
        province = bean.getResult().getBusiness().getProvince_info();
        city = bean.getResult().getBusiness().getCity_info();
        area = bean.getResult().getBusiness().getArea_info();
        street = bean.getResult().getBusiness().getStreet_info();
        address1 = bean.getResult().getBusiness().getProvince();
        address2 = bean.getResult().getBusiness().getCity();
        address3 = bean.getResult().getBusiness().getArea();
        address4 = bean.getResult().getBusiness().getStreet();
        signAddress = 4;
        isIsgn = true;

    }

    @Override
    public void onUserOutSuccess(MsgBean bean) {
        SPUtil.clear();    //清除 保存本地的数据
        boolean isClear = CacheManager.getInstance().clear();
        Logger.e("清除OKgo缓存~" + isClear);
        RxToast.success(bean.getMsg());
        $startActivityFinish(LoginActivity.class);
        //除了登录activity不关闭。其余的都关闭。
        MyApplication.getInstance().getActivityManager().popAllActivityExceptOne(LoginActivity.class);
    }

    @Override
    public void onShopUpSuccess(MsgBean bean) {
        RxToast.success(bean.getResult());
        RxBus.getDefault().post(new RxBusBean(200, 200));
        //todo 修改地址成功
    }

    @Override
    public void onProvinceListSuccess(AddressProvinceListBean bean) {
        if (bean.getResult() != null && bean.getResult().size() > 0) {
            mListCitys = bean.getResult();
        }
    }

    @Override
    public void onCityListSuccess(AddressProvinceListBean bean) {
        if (bean.getResult() != null && bean.getResult().size() > 0) {
            mListCitys = bean.getResult();
            if (!isIsgn)
                addressCheckAdapter.replaceData(mListCitys);
            else showCoupon();
        }
    }


    private void showCoupon() {
        if (popupWindowAddress != null && popupWindowAddress.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_address, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowAddress = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_address)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowAddress.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            //todo
            case R.layout.pw_address:
                RecyclerView rvCoupon = view.findViewById(R.id.recyclerView);
                rvCoupon.setLayoutManager(new LinearLayoutManager(getMe()));
                TextView tv_1 = view.findViewById(R.id.tv_1);
                TextView tv_2 = view.findViewById(R.id.tv_2);
                TextView tv_3 = view.findViewById(R.id.tv_3);
                TextView tv_4 = view.findViewById(R.id.tv_4);

                if (!TextUtils.isEmpty(province)) {
                    tv_1.setText(province);
                    tv_1.setVisibility(View.VISIBLE);
                }
                if (!TextUtils.isEmpty(city)) {
                    tv_2.setVisibility(View.VISIBLE);
                    tv_2.setText(city);
                }

                if (!TextUtils.isEmpty(area)) {
                    tv_3.setVisibility(View.VISIBLE);
                    tv_3.setText(area);
                }

                if (!TextUtils.isEmpty(street)) {
                    tv_4.setVisibility(View.VISIBLE);
                    tv_4.setText(street);
                }

                tv_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(tv_2.getText().toString().toString())) {
                            tv_1.setText("");
                            tv_1.setVisibility(View.GONE);
                            signAddress = 1;
                            address1 = 0;
                            province = "";
                            isIsgn = false;
                            mPresenter.onCityListData(1);
                        }

                    }
                });
                tv_2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(tv_3.getText().toString().toString())) {
                            tv_2.setText("");
                            tv_2.setVisibility(View.GONE);
                            address2 = 0;
                            signAddress = 2;
                            city = "";
                            isIsgn = false;
                            mPresenter.onCityListData(address1);
                        }
                    }
                });
                tv_3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (TextUtils.isEmpty(tv_4.getText().toString().toString())) {
                            tv_3.setText("");
                            tv_3.setVisibility(View.GONE);
                            signAddress = 3;
                            address3 = 0;
                            area = "";
                            isIsgn = false;
                            mPresenter.onCityListData(address2);
                        }
                    }
                });
                tv_4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tv_4.setText("");
                        tv_4.setVisibility(View.GONE);
                        signAddress = 4;
                        address4 = 0;
                        street = "";
                        isIsgn = false;
                        mPresenter.onCityListData(address3);
                    }
                });
                //创建适配器
                addressCheckAdapter = new AddressCheckAdapter(R.layout.pw_address_item, mListCitys);
                //给RecyclerView设置适配器
                rvCoupon.setAdapter(addressCheckAdapter);
                addressCheckAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        if (signAddress == 1) {
                            tv_1.setVisibility(View.VISIBLE);
                            tv_1.setText(addressCheckAdapter.getItem(position).getName());
                            address1 = addressCheckAdapter.getItem(position).getId();
                            signAddress = 2;
                            province = tv_1.getText().toString().trim();
                            isIsgn = false;
                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        } else if (signAddress == 2) {
                            tv_2.setVisibility(View.VISIBLE);
                            tv_2.setText(addressCheckAdapter.getItem(position).getName());
                            address2 = addressCheckAdapter.getItem(position).getId();
                            city = tv_2.getText().toString().trim();
                            signAddress = 3;
                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        } else if (signAddress == 3) {
                            tv_3.setVisibility(View.VISIBLE);
                            tv_3.setText(addressCheckAdapter.getItem(position).getName());
                            address3 = addressCheckAdapter.getItem(position).getId();
                            area = tv_3.getText().toString().trim();
//                            tvUserAddress.setText(province + city + area);
                            signAddress = 4;
                            isIsgn = false;
                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        } else {
                            tv_4.setVisibility(View.VISIBLE);
                            tv_4.setText(addressCheckAdapter.getItem(position).getName());
                            address4 = addressCheckAdapter.getItem(position).getId();
                            street = tv_4.getText().toString().trim();
                            tvUserAddress.setText(province + city + area + street);
                            LoggerUtils.e("地址：" + province + city + area + street);
                            popupWindowAddress.dismiss();
                            mPresenter.onShopUpData(LoginHelper.getLonginData().getResult(), address1, address2, address3, address4);
                        }

                    }
                });

                view.findViewById(R.id.tv_btn_colce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindowAddress.dismiss();
                    }
                });
                break;
        }
    }
}
